import { useState } from "react";
import axios from "axios";
import { Upload } from "../../component";
import { message } from "antd";
const Add = () => (
  <div
    style={{
      width: 200,
      height: 200,
      border: "1px solid #ccc",
      fontSize: 200,
      display: "flex",
      justifyContent: "center",
      alignItems: "center",
    }}
  >
    +
  </div>
);
const Home = () => {
  const [url, setUrl] = useState("");
  const beforeUpload = (file: File) => {
    if (!file.type.includes("image")) {
      message.error("上传的必须是一张图片");
      return false;
    }
    if (file.size > 1024 * 2 * 1024) {
      message.error("上传图片最大为2MB");
      return false;
    }
    return true;
  };
  const upload = async (file: File) => {
    const formData = new FormData();
    formData.append("chunk", file, file.name);
    const resp = await axios.post("/api/upload/image", formData);
    const { data } = resp.data;
    const { url } = data;
    setUrl(url);
  };
  return (
    <div>
      <Upload beforeUpload={beforeUpload} upload={upload}>
        {url ? (
          <img
            src={url}
            width="200"
            height={200}
            style={{ objectFit: "cover" }}
            alt=""
          />
        ) : (
          <Add></Add>
        )}
      </Upload>
    </div>
  );
};
export default Home;
